import { getFriendListApi, getGroupListApi, searchUserApi } from '@renderer/api'
import { defineStore } from 'pinia'

interface StateType {
  userOptions: Array<any>
  searchList: Array<any>
}

const useList = defineStore('useList', {
  state: () =>
    ({
      // 用户页面的选项
      userOptions: [
        {
          id: 1,
          title: '新朋友',
          icon: 'icon-xinpengyou',
          bgc: '#fa9d3b',
          path: '/user/newFriend'
        },
        {
          id: 2,
          title: '添加好友',
          icon: 'icon-fasong',
          bgc: '#1485ee',
          path: '/user/addFriend'
        },
        {
          id: 3,
          title: '我的群聊',
          icon: 'icon-qunliao',
          bgc: '#6dda53',
          list: []
        },
        {
          id: 4,
          title: '我的好友',
          icon: 'icon-yonghu',
          bgc: '#64b6e8',
          list: []
        }
      ],
      searchList: []
    }) as StateType,
  actions: {
    // 获得好友列表
    getFriendList() {
      getFriendListApi().then((res) => {
        const list = res.data.rows.newList?.map((m) => {
          return m.list
        })
        const arr: any = []
        list.forEach((item) => {
          arr.push(...item)
          this.userOptions[3].list = [...arr]
        })
        this.userOptions[3].list.forEach((item) => {
          if (!item.avatar) {
            item.avatar =
              'https://zk-1314434456.cos.ap-chengdu.myqcloud.com/default_avatar.jpg'
          }
        })
      })
    },

    // 获得群聊列表
    getGroupList(page = 1) {
      getGroupListApi(page).then((res) => {
        const list = res.data.map((m) => {
          return {
            id: m.id,
            name: m.name,
            avatar: m.avatar
              ? m.avatar
              : 'https://default-1314434456.cos.ap-guangzhou.myqcloud.com/default_group_avatar.jpg',
            member: m.member,
            group: true,
            user_id: m.user_id
          }
        })
        if (page === 1) {
          this.userOptions[2].list = list
        } else {
          this.userOptions[2].list.push(...list)
        }
      })
    },

    // 搜索用户
    getSearchUser(keyword: string) {
      searchUserApi(keyword).then((res) => {
        console.log(res)
        this.searchList = res.data
      })
    }
  }
})

export default useList
